package user.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.Page;
import util.Sex;
import util.StringUtil;
import user.dao.UserDao;
import user.vo.User;

public class UserController extends HttpServlet{
	UserDao userDao = new UserDao();
	final int pageSize = 10;
	/**
	 * 分发器
	 */
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//设置响应编码
		//req.setCharacterEncoding("utf-8");
		//resp.setCharacterEncoding("utf-8");
		//获取参数
		String ope = req.getParameter("ope");
		String method = req.getMethod().toLowerCase();
		
		if(ope != null && "login".equals(ope)){
			login(req,resp);
		}else if(ope != null && "showAllUser".equals(ope)){
			showAllUser(req,resp);
		}
		else if(ope != null && "addUser".equals(ope)){
			addUser(req,resp);
		}
		else if(ope != null && "delUser".equals(ope)){
			delUser(req,resp);
		}
		else if(ope != null && "editUser".equals(ope)){
			editUser(req,resp);
		}else if(ope != null && "submitUser".equals(ope)){
			submitUser(req,resp);
		}
		else if(ope != null && "viewUser".equals(ope)){
			viewUser(req,resp);
		}else if(ope != null && "changePwds".equals(ope)){
			changePwd(req,resp);
		}else if(ope != null && "exit".equals(ope)){
			exit(req,resp);
		}else if(ope != null && "search".equals(ope)){
			search(req,resp);
		}else if(ope != null && "page".equals(ope)){
			page(req,resp);
		}else if (ope != null && "queryByPage".equals(ope)){
			queryByPage(req,resp);
		}else{
			error(req,resp,"获取ope消息不正确："+ope);
			return;
		}
		
	}
	/**
	 * 根据查询条件，分页显示数据
	 */
	private void queryByPage(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		String loginname = req.getParameter("loginname");
		String showAll = req.getParameter("showAll");
		if(null == loginname && null != req.getSession().getAttribute("loginname")&&!"true".equals(showAll)){
			loginname = (String) req.getSession().getAttribute("loginname");
		}
		if(null == loginname){
			loginname = "";
		}
		String [] queryField = {"loginname"};
		String [] valueField = {loginname};
		String pageNum = req.getParameter("pageNum");//当前页数
		if(null == pageNum || "".equals(pageNum)){
			pageNum="1";
		}
		try {
			List<User> temp = userDao.query(queryField,valueField);
			int rowCount = temp.size();
			Page<User> page = new Page<User>(rowCount,pageNum,new Integer(pageSize).toString());
			List<User> userList = userDao.queryByPage(queryField,valueField,page.getRowNum(), page.getPageSize());
			page.setList(userList);
			req.setAttribute("pageUtil", page);
			req.getSession().setAttribute("loginname", loginname);
			req.getRequestDispatcher("user/index.jsp").forward(req, resp);
			return;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	/**
	 * 分页查询
	 * @param req
	 * @param resp
	 */
	private void page(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		String pageNum = req.getParameter("pageNum");//当前页数
		if(null == pageNum || "".equals(pageNum)){
			pageNum="1";
		}
		int rowCount ;//数据总量
		int pageCount ;//总页数
		int rowNum = (Integer.parseInt(pageNum)-1)*pageSize;
		
		try {
			List<User> ul = userDao.page(rowNum,pageSize);
			rowCount = userDao.getRowCount();
			Page page = new Page(rowCount,pageNum,"10");
			page.setList(ul);
			/*pageCount = (int)Math.ceil(rowCount*1.0/pageSize);
			req.setAttribute("userList",ul);
			req.setAttribute("pageNum", pageNum);
			req.setAttribute("rowCount",rowCount);
			req.setAttribute("rowNum",rowNum);
			req.setAttribute("pageCount",pageCount);*/
			req.setAttribute("pageUtil", page);
			req.getRequestDispatcher("user/index.jsp").forward(req, resp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	/**
	 * 查询
	 * @param req
	 * @param resp
	 */
	private void search(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		String loginname = req.getParameter("loginname");
		String [] queryField = {"loginname"};
		String [] valueField = {loginname};
		try {
			List<User> userList = userDao.query(queryField,valueField);
			req.setAttribute("userList",userList);
			for(int i =0;i<queryField.length;i++){
				req.setAttribute(queryField[i],valueField[i]);
			}
			req.getRequestDispatcher("user/index.jsp").forward(req, resp);
			return;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			this.error(req, resp, "查询失败");
			return;
		}
	}

	/**
	 * 修改密码
	 * @param req
	 * @param resp
	 */
	private void changePwd(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		String newpwd = req.getParameter("newpwd");
		User u = (User) req.getSession().getAttribute("user");
		u.setPwd(newpwd);
		try {
			userDao.updateUser(u,"pwd",newpwd);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			this.error(req, resp, "修改密码失败");
		}
		try {
			req.getSession().invalidate();
			resp.getWriter().print("<script type='text/javascript'>");
			resp.getWriter().print("alert('密码修改成功，请重新登陆');");
			resp.getWriter().print("top.location.href='"+req.getContextPath()+"/login.jsp'");
			resp.getWriter().print("</script>");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 退出登录
	 * @param req
	 * @param resp
	 */
	private void exit(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		req.getSession().invalidate();//强制销毁sessioin
		try {
			resp.sendRedirect(req.getContextPath()+"/login.jsp");
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 提交修改的用户信息
	 * @param req
	 * @param resp
	 */
	private void submitUser(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		String id = req.getParameter("id");
		String loginName = req.getParameter("loginName");
		String userName = req.getParameter("userName");
		String sex = req.getParameter("sex");
		Sex s = Sex.男;
		if("女".equals(sex)){
			s = Sex.女;
		}
		String age = req.getParameter("age");
		User u = new User();
		u.setId(Integer.parseInt(id));
		u.setLoginName(loginName);
		u.setUserName(userName);
		u.setSex(s);
		u.setAge(Integer.parseInt(age));
		boolean flag = userDao.editUser(u);
		if(flag){
			showAllUser(req, resp);
		}else{
			try {
				req.getRequestDispatcher("error.jsp").forward(req, resp);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			req.setAttribute("errorMsg", "添加用户失败");
		}
	
		
	}

	/**
	 * 编辑时获取用户信息
	 * @param req
	 * @param resp
	 */
	private void editUser(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		this.getUserById(req, resp, "submitUser");
	}

	/**
	 * 查看用户
	 * @param req
	 * @param resp
	 */
	private void viewUser(HttpServletRequest req, HttpServletResponse resp) {
		this.getUserById(req, resp, "viewUser");
	}
	
	private void getUserById(HttpServletRequest req, HttpServletResponse resp,String ope){
		// TODO Auto-generated method stub
		String id = req.getParameter("id");
		if(null == id || "".equals(id)){
			this.error(req, resp, "id为空");
			return;
		}
		User user;
		try {
			user = userDao.viewUser(id);
			if(null != user){
				req.removeAttribute("ope");
				req.setAttribute("ope", ope);
				req.setAttribute("user",user);
				req.getRequestDispatcher("user/addform.jsp").forward(req, resp);
				return;
			}else{
				this.error(req, resp, "没有查到用户信息");
				return;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			this.error(req, resp, "系统错误:"+e.getMessage());
			return;
		}
	
		
	}

	/**
	 * 删除用户
	 * @param req
	 * @param resp
	 */
	private void delUser(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		String id = req.getParameter("id");
		if(null == id || "".equals(id)){
			error(req, resp,"用户id为空");
			return;
		}
		boolean flag = userDao.delUser(id);
		if(flag){
			this.queryByPage(req, resp);
		}else{
			this.error(req, resp, "删除失败");
		}
	}

	/**
	 * 添加用户
	 * @param req
	 * @param resp
	 * @throws UnsupportedEncodingException 
	 */
	private void addUser(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
		// TODO Auto-generated method stub
		String loginName = req.getParameter("loginName");
		String pwd = req.getParameter("pwd");
		String pwdCfm = req.getParameter("pwdCfm");
		String userName = req.getParameter("userName");
		String sex = req.getParameter("sex");
		Sex s = Sex.男;
		if("女".equals(sex)){
			s = Sex.女;
		}
		String age = req.getParameter("age");
		try {
			if(null == pwd || "".equals(pwd) || null == pwdCfm || "".equals(pwdCfm)){
				error(req,resp,"密码不能为空");
				return;
			}else if(!pwd.equals(pwdCfm)){
				error(req,resp,"输入密码不一致!"+pwd+":"+pwdCfm);
				return;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		User u = new User(loginName,pwd,userName,s,Integer.parseInt(age));
		boolean flag = userDao.addUser(u);
		if(flag){
			showAllUser(req, resp);
		}else{
			try {
				req.getRequestDispatcher("error.jsp").forward(req, resp);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			req.setAttribute("errorMsg", "添加用户失败");
		}
	
		
	}

	/**
	 * 显示所有用户信息
	 * @param req
	 * @param resp
	 */
	private void showAllUser(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		List<User> userList;
		try {
			userList = userDao.showAllUser();
			if(userList != null){
				req.setAttribute("userList",userList);
				req.getRequestDispatcher("user/index.jsp").forward(req, resp);
			}else{
				error(req,resp,"获取用户信息失败");
				return;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 登录验证
	 * @param req
	 * @param resp
	 */
	private void login(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		String loginName = req.getParameter("loginName");
		String pwd = req.getParameter("pwd");
		try{
			if(StringUtil.isEmpty(loginName)){
				req.getSession().setAttribute("errorMsg", "登录失败，账号不能为空!");
				resp.sendRedirect("login.jsp");
				return;
			}else if(StringUtil.isEmpty(pwd)){
				req.getSession().setAttribute("errorMsg", "登录失败，密码不能为空!");
				req.setAttribute("loginName", loginName);
				req.getRequestDispatcher("login.jsp").forward(req, resp);
				return;
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		
		//验证登录
		try {
			User user = userDao.login(loginName, pwd);
			if(user !=  null){
				//成功，跳转到成功页面
				req.getSession().setAttribute("user", user);
				//req.getRequestDispatcher("index.jsp").forward(req, resp);
				req.getRequestDispatcher("main.jsp").forward(req,resp);
			}else{
				//失败，显示失败信息，重定向到登录页面
				req.getSession().setAttribute("errorMsg", "登录失败，请重新登录!");
				resp.sendRedirect("login.jsp");
				return;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 错误
	 * @param req
	 * @param resp
	 * @param string
	 */
	private void error(HttpServletRequest req, HttpServletResponse resp,
			String errorMsg) {
		// TODO Auto-generated method stub
		req.setAttribute("errorMsg",errorMsg);
		try {
			req.getRequestDispatcher("error.jsp").forward(req, resp);
		} catch (ServletException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
